Fork me on GitHub

14. Longest Common Prefix

\14. Longest Common Prefix

Easy

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

1
2
Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

1
2
3
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
  1. 终极改良版
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0: return ''

prefix = strs[0]
for s in strs[1:]:
prefix = self.same(prefix, s)
if not prefix: return ''
return prefix

def same(self, s1, s2):
res = ''
if not s1 or not s2: return res
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
return s1[:i]
return s1 if len(s1) <= len(s2) else s2
Shuolin Tian wechat
欢迎加我微信交流